<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <!-- 班级搜索表单 -->
    <el-form :model="classQuery" ref="classQueryForm" :inline="true" label-width="100px">
      <el-form-item label="班级名称">
        <el-input v-model="classQuery.className" placeholder="请输入班级名称" clearable size="small" style="width: 240px" />
      </el-form-item>
      <el-form-item label="授课老师">
        <el-input v-model="classQuery.teacher" placeholder="请输入老师姓名" clearable size="small" style="width: 240px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="getClassList">搜索</el-button>
        <el-button size="mini" icon="el-icon-refresh" @click="resetClassQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button plain type="primary" icon="el-icon-plus" size="mini" @click="handleAddClass">
          新增班级
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getStudentList" />
    </el-row>

    <!-- 班级列表 -->
    <el-card class="mb16" shadow="hover">
      <div slot="header" class="clearfix">
        <span>班级管理</span>
      </div>
      <el-table :data="classOptions" v-loading="classTableLoading" border stripe>
        <el-table-column label="班级编号" align="center" prop="classId" />
        <el-table-column label="班级名称" align="center" prop="className" />
        <el-table-column label="授课老师" align="center" prop="teacher" />
        <el-table-column label="开班日期" align="center">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结班日期" align="center">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="260">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="viewStudents(scope.row)">查看学生</el-button>
            <el-button type="warning" size="mini" @click="handleEditClass(scope.row)">修改</el-button>
            <el-button type="danger" size="mini" @click="deleteClass(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <pagination
      v-show="classTotal > 0"
      :total="classTotal"
      :page.sync="classQuery.pageNum"
      :limit.sync="classQuery.pageSize"
      @pagination="getClassList"
    />

    <!-- 学生搜索表单 -->
    <el-form :model="studentQuery" ref="studentQueryForm" :inline="true" label-width="100px">
      <el-form-item label="学生姓名">
        <el-input v-model="studentQuery.studentName" placeholder="请输入学生姓名" clearable size="small" style="width: 240px" />
      </el-form-item>
      <el-form-item label="所属班级">
        <el-select v-model="studentQuery.classId" placeholder="请选择班级" clearable size="small" style="width: 240px">
          <el-option v-for="c in classOptions" :key="c.id" :label="c.className" :value="c.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="getStudentList">搜索</el-button>
        <el-button size="mini" icon="el-icon-refresh" @click="resetStudentQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 学生列表 -->
    <el-card shadow="hover">
      <div slot="header" class="clearfix">
        <span>学生列表</span>
      </div>

      <el-table v-loading="loading" :data="studentList" border stripe>
        <el-table-column label="ID" align="center" prop="id" width="60" />
        <el-table-column label="学生姓名" align="center" prop="studentName" />
        <el-table-column label="英文名" align="center" prop="studentEnglishName" />
        <el-table-column label="性别" align="center" prop="gender" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.gender }}</span>
          </template>
        </el-table-column>

        <el-table-column label="所属班级" align="center" width="220">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.className"
              placeholder="请选择班级"
              size="mini"
              style="width: 180px"
              clearable
              @change="val => handleAssign(scope.row, val)"
            >
              <el-option
                v-for="item in classOptions"
                :key="item.classId"
                :label="item.className"
                :value="item"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="生日" align="center" prop="birthday" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="家长ID" align="center" prop="relatedParent" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="studentQuery.pageNum"
        :limit.sync="studentQuery.pageSize"
        @pagination="getStudentList"
      />

    </el-card>

    <el-dialog
      :title="title"
      :visible.sync="openClassDialog"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="classForm"
        :model="classForm"
        :rules="classRules"
        label-width="120px"
      >
        <el-form-item label="班级编号" prop="classId">
          <el-input v-model="classForm.classId" placeholder="例如：Class_A01" clearable />
        </el-form-item>

        <el-form-item label="班级名称" prop="className">
          <el-input v-model="classForm.className" placeholder="请输入班级名称" clearable />
        </el-form-item>

        <el-form-item label="授课老师" prop="teacher">
          <el-input v-model="classForm.teacher" placeholder="请输入授课老师" clearable />
        </el-form-item>

        <el-form-item label="开班日期" prop="startDate">
          <el-date-picker
            v-model="classForm.startDate"
            type="date"
            placeholder="请选择开班日期"
            value-format="yyyy-MM-dd"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="结班日期" prop="endDate">
          <el-date-picker
            v-model="classForm.endDate"
            type="date"
            placeholder="请选择结班日期"
            value-format="yyyy-MM-dd"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="openClassDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitClass">确 定</el-button>
      </div>
    </el-dialog>



    <el-dialog :title="studentDialogTitle" :visible.sync="open" width="500px" :close-on-click-modal="false" append-to-body>
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入学生姓名" />
        </el-form-item>

        <el-form-item label="英文名" prop="studentEnglishName">
          <el-input v-model="form.studentEnglishName" placeholder="请输入英文名" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>

        <el-form-item label="生日" prop="birthday">
          <el-date-picker v-model="form.birthday" type="date" placeholder="选择生日" value-format="yyyy-MM-dd" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listAll,
  listAllClass,
  saveClass,
  updateStudentClass,
  listStudents,
  updateClassInfo,
  deleteById,
  updateStudentInfo,
  deleteStudentById
} from "@/api/student/studentInfo";
import {parseTime} from "../../../utils/common";

export default {
  name: "StudentClassManage",
  data() {
    return {
      loading: false,
      classTotal: 0,
      showSearch: true,
      classQuery: {
        pageNum: 1,
        pageSize: 10,
        className: undefined,
        teacher: undefined
      },
      // 学生查询参数
      studentQuery: {
        pageNum: 1,
        pageSize: 10,
        studentName: undefined,
        classId: undefined
      },
      open: false,
      studentDialogTitle: '',
      form: {
        studentName: "",
        studentEnglishName: "",
        gender: "",
        birthday: ""
      },
      studentList: [],
      total: 0,
      classOptions: [],
      openClassDialog: false,
      title: "",
      classForm: {
        classId: '',
        className: '',
        teacher: '',
        startDate: '',
        endDate: '',
      },

      classRules: {
        className: [{ required: true, message: "班级名称不能为空", trigger: "blur" }]
      },
      classLoading: false, // ✅ 班级加载状态
      classPageNum: 1,
      classPageSize: 10,
      classHasMore: true,
      classTableLoading: false, // ✅ 班级加载状态
      classMap: {}, // ✅ 班级ID与名称映射
    };
  },
  created() {
    this.getAllClass().then(() => {
      this.getStudentList();
    });
    //this.getStudentList();
  },
  methods: {
    parseTime,
    getClassList() {
      this.getAllClass();
    },

    /** 重置班级查询 */
    resetClassQuery() {
      this.resetForm("classQueryForm");
      this.getClassList();
    },

    /** 获取学生列表 */


    /** 重置学生查询 */
    resetStudentQuery() {
      this.resetForm("studentQueryForm");
      this.getStudentList();
    },
    handleEditClass(row) {
      this.classForm = {
        id: row.id,
        classId: row.classId,
        className: row.className,
        teacher: row.teacher,
        startDate: row.startDate ? row.startDate.substring(0, 10) : '',
        endDate: row.endDate ? row.endDate.substring(0, 10) : ''
      };
      this.openClassDialog = true;
      this.title = "修改班级";
    },

    searchClass(keyword) {
      this.classLoading = true;
      // 调用分页接口
      listAllClass({
        pageNum: 1,
        pageSize: 10,
        className: keyword || ''
      }).then(res => {
        this.classOptions = res.rows || [];
        this.classLoading = false;
      });
    },
    /** 获取所有班级 */
    getAllClass() {
      this.classTableLoading = true;
      return listAllClass(this.classQuery).then(res => {
        // ✅ 全部转为字符串，保持和 student.classId 一致
        this.classOptions = (res.rows || []).map(c => ({
          ...c,
          id: String(c.id)
        }));

        this.classTotal = Number(res.total) || 0;
      }).finally(() => {
        this.classTableLoading = false;
      });
    },
    getStudentList() {
      this.loading = true;
      console.log(this.studentQuery)
      listAll(this.studentQuery).then((res) => {
        this.studentList = res.rows;
        this.total = Number(res.total) || 0;
      }).finally(() => {
        this.loading = false;
      });
    },

    /** 修改学生 */
    handleEdit(row) {
      this.form = { ...row };
      this.open = true;
      this.studentDialogTitle = "修改学生信息";
    },

    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          updateStudentInfo(this.form).then(() => {
            this.msgSuccess("保存成功");
            this.open = false;
            this.getStudentList();
          });
        }
      });
    },
    /** 删除学生 */
    handleDelete(id) {
      this.$confirm("确认删除该学生吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 如果你的删除接口名不同，请在这里换成对应方法
          deleteStudentById(id).then(() => {
            this.msgSuccess("删除成功");
            this.getStudentList();
          });
        })
        .catch(() => {});
    },



    /** 查看某班级学生 */
    viewStudents(row) {
      this.studentQuery.classId = row.id;
      this.getStudentList();
    },


    /** 分配或修改班级 */
    handleAssign(studentRow, selected) {
      const payload = {
        studentId: studentRow.id,
        newClassId: selected ? selected.id : null
      };
      updateStudentClass(payload).then(() => {
        // ✅ 同步更新显示字段
        studentRow.classId = selected ? selected.id : null;
        studentRow.className = selected ? selected.className : null;
        this.msgSuccess("班级分配成功");
        this.getStudentList();
      });
    },



    /** 新增班级 */
    handleAddClass() {
      this.classForm = { className: "" };
      this.openClassDialog = true;
      this.title = "新增班级";
    },
    /** 提交新增班级 */
    submitClass() {
      this.$refs["classForm"].validate(valid => {
        if (!valid) return;

        const request = this.classForm.id
          ? updateClassInfo(this.classForm)
          : saveClass(this.classForm);

        request.then(() => {
          this.msgSuccess(this.classForm.id ? "修改成功" : "新增成功");
          this.openClassDialog = false;
          this.getAllClass();
        });
      });
    },
    /** 删除班级 */
    deleteClass(id) {
      this.$confirm("确认删除该班级吗？删除后学生将无班级关联。", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteById(id).then(() => {
          this.msgSuccess("删除成功");
          this.getAllClass();
        });
      });
    }
  }
};
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
.mb16 {
  margin-bottom: 16px;
}
</style>
